var express = require('express')
var opn = require('opn')
var mongoose = require('mongoose')
var path = require('path')
var bodyParser = require('body-parser');

var BookModelBuilder = require('./server/BookModelBuilder.js')

var app = express()

//post请求体安全获取
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname, 'client')));

app.get('/', function (req,res) {
  res.render('index')
})


/*数据库逻辑*/

var db = mongoose.createConnection('localhost','test')

db.on('error', console.error.bind(console,'数据库连接失败,请确保已经开启mongodb数据库服务\r\n') )
db.once('open', function () {
  console.log('数据库已连接')
})

var BookModel = BookModelBuilder(db)


//获取数据
app.get('/fetch', function (req, res) {
  BookModel.find({}, function (err,books) {
    res.send(books)
  })
})
//添加数据
app.post('/add', function (req, res) {
  (new BookModel(req.body)).save()
  res.send('1')
})

//删除数据
app.post('/delete', function (req, res) {
  BookModel.remove({_id: req.body._id}, function () {
    res.send('1')
  })
})

//更新数据
app.post('/update', function (req, res) {
  var book = req.body;
  BookModel.update({_id: book._id}, {$set: book}, function (err,result) {
    if (err) return err;
  })
  res.send('1')
})
/*数据互交结束*/

//跨域
app.all('*', (req, res, next) => {
  const origin = req.headers.origin;
  res.header('Access-Control-Allow-Origin', origin);
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, token');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS, DELETE');

  next();
});


app.listen(8080)
console.log('正在监听：8080端口')

opn('http://localhost:8080')